package com.test25_常用类2;

import org.junit.Test;

import java.util.Arrays;

/**
 * Arrays，数组操作类
 */
public class Demo06_Arrays {

    /**
     * 数组排序
     */
    @Test
    public void test1() {
        int[] data = new int[] {1, 5, 7, 2, 90, 23, 56, 78};
        System.out.println("【原始数组内容】" + Arrays.toString(data));
        Arrays.sort(data);  // 数组排序
        System.out.println("【排序后的数组】" + Arrays.toString(data));
    }

    /**
     * 数组比较
     */
    @Test
    public void test2() {
        int[] dataA = new int[] {1, 7, 5};
        int[] dataB = new int[] {5, 7, 1};
        System.out.println("【相等判断 - 未排序】" + Arrays.equals(dataA, dataB));
        Arrays.sort(dataA);
        Arrays.sort(dataB);
        System.out.println("【相等判断 - 已排序】" + Arrays.equals(dataA, dataB));
    }

    /**
     * 数组内容查找
     */
    @Test
    public void test3() {
        int[] data = new int[] {9, 8, 5, 19, 29, 56, 78, 3};
        int key = 9;
        System.out.println(Arrays.binarySearch(data, key));
        Arrays.sort(data);
        System.out.println("【数组排序】" + Arrays.toString(data));
        System.out.println(search(data, key));
        System.out.println(binarySearch(data, key));
        System.out.println(Arrays.binarySearch(data, key));
    }

    /** 遍历查找 */
    public static int search(int[] data, int key) {
        for (int x = 0; x < data.length; x++) {
            if (data[x] == key) {
                return x;
            }
        }
        return -1;
    }

    /** 二分法查找 */
    public static int binarySearch(int[] data, int key) {
        int low = 0;
        int high = data.length - 1;
        while (low <= high) {
            int mid = (low + high) >>> 1;   // 进行中间索引的确定，折半
            int midVal = data[mid];
            if (midVal < key)
                low = mid + 1;
            else if (midVal > key)
                high = mid - 1;
            else
                return mid;
        }
        return -(low + 1);
    }
}
